package com.dream.utils.file;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.util.LinkedList;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.dream.utils.file.DiffMatchPatch.Diff;
import com.dream.utils.io.FileIOUtils;
import com.dream.utils.log.DreamLogUtils;

public class FileDiffMatchPatch {
	
	private static LinkedList<Diff> diffTxtFile(String one , String two){
		
		LinkedList<Diff> list = new LinkedList<Diff>();
		BufferedReader oneReader = FileIOUtils.fileBufferedReader(one);
		BufferedReader twoReader = FileIOUtils.fileBufferedReader(two);
		StringBuilder oneBulder = new StringBuilder();
		StringBuilder twoBulder = new StringBuilder();
		try{
			
			for(String line = oneReader.readLine();line != null;){
				oneBulder.append(line);
				line = oneReader.readLine();
			}
			
			for(String line = twoReader.readLine();line != null;){
				twoBulder.append(line);
				line = twoReader.readLine();
			}
			
			list = new DiffMatchPatch().diff_main(oneBulder.toString(), twoBulder.toString(), true);
		} catch (Exception e) {
			DreamLogUtils.error(FileDiffMatchPatch.class, "diffFile", "", e);
			throw new RuntimeException(e);
		}finally{
			FileIOUtils.close(oneReader);
			FileIOUtils.close(twoReader);
		}
		return list;
	}
	
	public static LinkedList<Diff> diffFile(String one , String two){
		
		if(one.toLowerCase().contains(".txt")){
			return diffTxtFile(one,two);
		}
		
		if(one.toLowerCase().contains(".doc") || one.toLowerCase().contains(".docx")){
			return diffDocFile(one,two);
		}
		
		return new LinkedList<Diff>();
	}
	
	@SuppressWarnings("resource")
	private static LinkedList<Diff> diffDocFile(String one , String two){
		
		LinkedList<Diff> list = new LinkedList<Diff>();
		FileInputStream fone = null;
		FileInputStream ftwo = null;
		try{
		
			 fone = new FileInputStream(one);     
		     XWPFDocument xd = new XWPFDocument(fone);
		     XWPFWordExtractor extractor = new XWPFWordExtractor(xd);//word 2007
		     String textOne = extractor.getText();   
		     
			 ftwo = new FileInputStream(two);     
			 XWPFDocument xdTwo = new XWPFDocument(ftwo);
			 XWPFWordExtractor extractorTwo = new XWPFWordExtractor(xdTwo);//word 2007
			 String textTwo = extractorTwo.getText();    
		     
		     list = new DiffMatchPatch().diff_main(textOne, textTwo, true);
		} catch (Exception e) {
			DreamLogUtils.error(FileDiffMatchPatch.class, "diffFile", "", e);
			throw new RuntimeException(e);
		}finally{
			FileIOUtils.close(fone);
			FileIOUtils.close(ftwo);
		}
		
		return list;
	}
}
